﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using System.Web.Routing;

namespace ScrumDashboardMvc.Html
{
    public static class MarkupExtensions
    {
        public static string Clip(this HtmlHelper helper, string str, int count)
        {
            if (str.Length == 0)
            {
                return "(empty)";
            }
            else
            {
                return str.Length > count ? str.Substring(0, count) + ".." : str;
            }
        } 
        public static void RenderUnorderedList<T>(this HtmlHelper helper, IEnumerable<T> items, string partialViewName)
        {
            helper.RenderUnorderedList<T>(items, partialViewName, null, null);
        }
        public static void RenderUnorderedList<T>(this HtmlHelper helper, IEnumerable<T> items, string partialViewName, object ulHtmlAttributes)
        {
            helper.RenderUnorderedList<T>(items, partialViewName, ulHtmlAttributes, null);
        }
        public static void RenderUnorderedList<T>(this HtmlHelper helper, IEnumerable<T> items, string partialViewName, object ulHtmlAttributes, object liHtmlAttributes)
        {
            helper.RenderUnorderedList<T>(items, item => helper.RenderPartial(partialViewName, item), ulHtmlAttributes, liHtmlAttributes);
        }

        public static void RenderUnorderedList<T>(this HtmlHelper helper, IEnumerable<T> items, Action<T> renderTemplate, object ulHtmlAttributes, object liHtmlAttributes)
        {
            TagBuilder ul = new TagBuilder("ul");
            if (ulHtmlAttributes != null)
                ul.MergeAttributes(new RouteValueDictionary(ulHtmlAttributes));
            TagBuilder li = new TagBuilder("li");
            if (liHtmlAttributes != null)
                li.MergeAttributes(new RouteValueDictionary(liHtmlAttributes));
            
            bool first = true;
            foreach (var item in items)
            {
                if (first)
                {
                    first = false;
                    helper.ViewContext.Writer.Write(ul.ToString(TagRenderMode.StartTag));
                }
                helper.ViewContext.Writer.Write(li.ToString(TagRenderMode.StartTag));
                renderTemplate(item);
                helper.ViewContext.Writer.Write(li.ToString(TagRenderMode.EndTag));
            }
            if (!first)
            {
                helper.ViewContext.Writer.Write(ul.ToString(TagRenderMode.EndTag));
            }
        }
    }
}